<?php
/**
* This controller generates the GlobalView for both the FRONTEND and ADMIN
* environments.
*
* Copyright (c) 2009 James Gauld <james@jamesgauld.net>
* This file is part of Scribble.
* @license http://www.scribblecms.co.uk/license.txt
*
* @package Scribble
*/
use Buan\Config;
use Buan\ControllerException;
use Buan\Core;
use Buan\Model;
use Buan\ModelException;
use Buan\UrlCommand;
class GlobalViewController extends ScribblePublicController {

	/**
	* Return a View using the "default" outer template and a blank Page model.
	* This method should only be called when a request for an unknown page is
	* made (ie. HTTP 404)
	*
	* @param array Action parameters (none supported)
	* @return ScribblePublicView
	*/
	public function index($params) {

		// Check for a pre-generated View
		static $v = NULL;
		if($v!==NULL) {
			return $v;
		}

		// Generate view for current environment
		if(ScribbleEnvironment::isAdmin()) {
			return $v = $this->envAdmin();
		}
		else if(ScribbleEnvironment::isFrontend()) {
			return $v = $this->envFrontend();
		}
		else {
			die("Unknown environment");
		}
	}

	/**
	* Generates a View for the ADMIN environment.
	*
	* @return ScribbleAdminView
	*/
	private function envAdmin() {
		$GV = new ScribbleAdminView();
		$GV->setHeader('Content-Type', 'text/html; charset=utf-8');
		$GV->setSource(Config::get('ext.Scribble.dir.views').'/global-view/index.tpl.php');
		$slView = new ScribbleAdminView();
		$slView->setSource(Config::get('ext.Scribble.dir.views').'/global-view/system-log.tpl.php');
		$GV->attachViewToSlot($slView, 'systemlog');
		return $GV;
	}

	/**
	* Generates a View for the FRONTEND environment based on the default outer
	* view.
	*
	* @return ScribblePublicView
	*/
	private function envFrontend() {
		$page = Model::create('Page');
		$version = Model::create('PageVersion');
		$page->addRelatives($version, 'master');
		$version->getOuterContent()->template = ScribbleTemplateManager::getDefaultOuterTemplate();
		try {
			$gview = $version->getOuterView();
		}
		catch(ModelException $e) {
			throw new ControllerException($e->getMessage());
		}

		// Add inline admin elements if an administrator is logged in
		if(ScribbleSession::isOccupied() && ScribbleAuth::authorize(ScribbleSession::getUser(), 'scribble-admin')) {
			$ur = Config::get('ext.Scribble.urlRoot');
			$gview->addStylesheets("{$ur}/inline/scribble-inline.css");
			$gview->addJavascripts(UrlCommand::createUrl('scribble', 'inline', 'js', array('p'=>$page->id)));
		}
		$gview->setHeader('Content-Type', 'text/html; charset=utf-8');
		return $gview;
	}
}
?>